python: save comments from configparser

Configparser is a standard python library that really lives up to its name. I often use it to handle simple configuration files.

Problem: my favorite standard for documenting configuration files is via comments. Configparser ignores comments (as expected), but this means that a programmatic change to a config file erases all comments.

Solution: I wrote a couple of functions to save and restore comments. This gets the job done, although I feel guilty for not overloading configparser. Someday…

(view on github)

#!/usr/bin/env python3

import configparser, re

config_file = "configparser-save-comments.conf"

def save_comments(config_file):
    """Save index and content of comments in config file and return dictionary thereof"""
    comment_map = {}
    with open(config_file, 'r') as file:
        i = 0
        lines = file.readlines()
        for line in lines:
            if re.match( r'^\s*#.*?$', line):
                comment_map[i] = line
            i += 1
    return comment_map

def restore_comments(config_file, comment_map):
    """Write comments to config file at their original indices"""
    with open(config_file, 'r') as file:
        lines = file.readlines()
    for (index, comment) in sorted(comment_map.items()):
        lines.insert(index, comment)
    with open(config_file, 'w') as file:
        file.write(''.join(lines))

# create map containing comment lines and their indices
comment_map = save_comments(config_file)
# open config file and load it into configparser
with open(config_file, 'r') as file:
    config = configparser.ConfigParser()
    config.read_string(file.read())
# change every value in the config file to "CLASSIFIED"
for section in config.sections():
    for key, value in config.items(section):
        config.set(section, key, "CLASSIFIED")
# write the new config to the config file
with open(config_file, 'w') as file:
    config.write(file)
# put the comments back in their original indices
restore_comments(config_file, comment_map)

Leave a comment